<script setup>
import { uniq } from 'lodash'
const checkDiskSpace = require('check-disk-space').default
const cmd = require('node-cmd')
const osUtils = require('os-utils')

const emits = defineEmits(['updateGames'])
const p = defineProps(['showGames'])
const visible = ref(false)
const diskList = ref([])
const monitor = ref({
  mem: {},
  cpu: {},
  gpu: {}
})

const getDiskList = (showGames) => {
  const disks = uniq(showGames.map((item) => item.path.split(':')[0]))
  diskList.value = new Array(disks.length)
  disks.map(async (disk, index) => {
    const res = await checkDiskSpace(disk + ':')
    const game = showGames.reduce((size, game) => size + (game.path.startsWith(disk) ? game.size : 0), 0)
    diskList.value.splice(index, 1, { ...res, name: disk, game, other: res.size - res.free - game })
  })
}

const onShell = () => {
  if (!visible.value || !window.isPageShow) return
  osUtils.cpuUsage((res) => {
    const { data } = cmd.runSync('nvidia-smi')
    const lines = data.split('\r\n')
    const index = lines.findIndex((item) => item.includes('='))
    const [fan, temperature, , curPower, , curMem, maxMem, usage] = lines[index + 2].match(/(\d+)/g)

    monitor.value = {
      gpu: { fan, temperature, curPower, memUsage: ((curMem / maxMem) * 100).toFixed(0), usage },
      mem: { usage: ((1 - osUtils.freememPercentage()) * 100).toFixed(0) },
      cpu: { usage: (res * 100).toFixed(0) }
    }
    onShell()
  })
}

const formatSize = (size) => {
  return (size / 1024 / 1024 / 1024).toFixed(1)
}

watch(visible, (v) => {
  !v && emits('updateGames')
  v && onShell()
})
watch(p, ({ showGames }) => getDiskList(showGames))

onMounted(() => {
  window.onpageshow = () => {
    onShell()
  }
})
</script>

<template>
  <v-btn class="float-btn" variant="tonal" :show="visible" icon="pi pi-chevron-up" @click="visible = !visible" />
  <Drawer v-model:visible="visible" position="bottom" style="height: 220px" :close-button-props="{ style: { display: 'none' } }">
    <v-row class="position-absolute w-100 h-100 top-0 left-0 ma-0">
      <!-- 文件夹管理 -->
      <list-component table-name="path" />
      <!-- 游戏目录管理 -->
      <list-component table-name="library" />
      <!-- 性能监控 -->
      <v-col sm="1" class="pr-0">
        <v-sheet border="primary thin" color="transparent" class="w-100 h-100" style="" rounded>
          <div class="montior-title">CPU</div>
          <div class="px-1 monitor-list">
            <Tag severity="secondary" :value="`占用 ${monitor.cpu.usage || 0}%`" />
          </div>
        </v-sheet>
      </v-col>
      <v-col sm="1" class="pr-0">
        <v-sheet border="warning thin" color="transparent" class="w-100 h-100" style="" rounded>
          <div class="montior-title">内存</div>
          <div class="px-1 monitor-list">
            <Tag severity="secondary" :value="`占用 ${monitor.mem.usage || 0}%`" />
          </div>
        </v-sheet>
      </v-col>
      <v-col sm="1" class="pr-0">
        <v-sheet border="success thin" color="transparent" class="w-100 h-100" style="" rounded>
          <div class="montior-title">显卡</div>
          <div class="px-1 monitor-list">
            <Tag severity="secondary" :value="`占用 ${monitor.gpu.usage || 0}%`" />
            <Tag severity="info" :value="`功耗 ${monitor.gpu.curPower || 0}W`" />
            <Tag severity="success" :value="`温度 ${monitor.gpu.temperature || 0}℃`" />
            <Tag severity="warn" :value="`风扇 ${monitor.gpu.fan || 0}%`" />
            <Tag severity="danger" :value="`显存 ${monitor.gpu.memUsage || 0}%`" />
          </div>
        </v-sheet>
      </v-col>
      <!-- 磁盘空间 -->
      <v-col sm="5" class="w-100 h-100">
        <v-sheet border="error thin" color="transparent" class="pa-1 w-100 h-100" style="" rounded>
          <div class="w-100 h-100 d-flex justify-space-evenly flex-column scroll-box">
            <div v-for="disk in diskList.sort((a, b) => a.name.localeCompare(b.name))" :key="disk.name" class="ma-1">
              <Chip class="rounded-xl w-100">
                <span
                  style="width: 30px; height: 30px; line-height: 30px; background: #fafafa; color: #212121"
                  class="d-inline-block rounded-xl text-center text-h6 font-weight-bold"
                >
                  {{ disk.name }}
                </span>
                <MeterGroup
                  :value="[
                    { label: '其他', color: '#1976D2', value: disk.other },
                    { label: '游戏', color: '#F57C00', value: disk.game }
                  ]"
                  :max="disk.size"
                  class="ga-1 flex-fill"
                >
                  <template #label="{ value }">
                    <ol class="p-metergroup-label-list p-metergroup-label-list-horizontal ga-2">
                      <li v-for="v in value" :key="v.label" class="p-metergroup-label rounded-xl px-2" style="background: rgba(255, 255, 255, 0.2)">
                        <span class="p-metergroup-label-marker" :style="{ background: v.color }" />
                        <span class="text-caption font-weight-thin"> {{ v.label }} ( {{ formatSize(v.value) }}GB / {{ ((v.value / disk.size) * 100).toFixed(1) }}% ) </span>
                      </li>
                    </ol>
                  </template>
                </MeterGroup>
                <span
                  style="width: 80px; height: 30px; line-height: 30px; background: #fafafa; color: #212121"
                  class="d-inline-block rounded-xl text-center text-caption px-2 font-weight-bold text-no-wrap"
                >
                  {{ formatSize(disk.free) }} <span class="font-weight-medium">GB</span>
                </span>
              </Chip>
            </div>
          </div>
        </v-sheet>
      </v-col>
    </v-row>
  </Drawer>
</template>

<style lang="css" scoped>
.float-btn {
  position: fixed;
  bottom: 20px;
  right: 20px;
  transition: opacity 0.3s 0.3s;
  z-index: 999;
  &[show='true'] {
    opacity: 0;
  }
}

.scroll-box {
  overflow: hidden auto;
  max-height: 100%;

  &::-webkit-scrollbar {
    width: 0.6rem;
    cursor: pointer;
  }

  &::-webkit-scrollbar-button {
    height: 2px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: #212121;
    border-radius: 8px;
  }
}

.v-sheet {
  overflow: hidden;
}

.montior-title {
  font-size: 1.2rem;
  line-height: 2.2rem;
  height: 2.7rem;
  text-align: center;
  background: linear-gradient(rgba(var(--v-border-color), 0.4) 0%, transparent 100%);
}

.monitor-list {
  & > span {
    width: 100%;
    margin-bottom: 4px;
    font-size: 12px;
    padding-left: calc(50% - 27px);
    justify-content: start;
  }
}
</style>
